package Day11.homework;


import java.util.concurrent.locks.ReentrantLock;

//使用公平锁ReentrantLock实现一个线程安全的计数器
//多个线程同时递增计数，最后输出正确结果
public class Count {
    int sum = 0;
    ReentrantLock lock = new ReentrantLock(true);
    public void  numAccount(){
        String name = Thread.currentThread().getName();
        lock.lock();
        sum++;
        System.out.println(name+"：+1");
        lock.unlock();
    }
    public void getAccount(){
        String name = Thread.currentThread().getName();
        lock.lock();
        System.out.println(name+"输出："+sum);
        lock.unlock();
    }

    public static void main(String[] args) {
        Count c = new Count();
        for (int i = 1; i < 6; i++) {
            new Thread(()->{
                c.numAccount();
                c.getAccount();
            },"线程"+i).start();
        }
    }
}
